﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Linq;

[assembly: WebResource("Churchtoolkit.Utils.Controls.DateControl.js", "text/javascript")]

namespace Churchtoolkit.Utils.Controls
{
    /// <summary>
    /// DateForm 
    /// </summary>
    [ToolboxData("<{0}:DateControl runat=server></{0}:DateControl>")]
    [ValidationPropertyAttribute("SelectedDate")]
    public class DateControl : CompositeControl
    {
        #region [ Constants ]
        private const string StartupScript = @"new DateControl('{0}', '{1}', '{2}');";
        #endregion

        #region [ private fields ]
        private readonly DropDownList _ddlDays;
        private readonly DropDownList _ddlMonths;
        private readonly DropDownList _ddlYears;

        private static IList _lstMonthItems;
        private static IList _lstYearItems;
        #endregion

        #region [ Constructor ]
        public DateControl()
        {
            _ddlDays = new DropDownList();
            _ddlMonths = new DropDownList();
            _ddlYears = new DropDownList();
        }
        static DateControl()
        {
            _lstMonthItems = new List<object>();
            for (int i = 1; i <= 12; i++)
                _lstMonthItems.Add(new
                {
                    Text = new DateTime(1990, i, 1).ToString("MMMM"),
                    Value = i.ToString()
                });
            //------------------------------------------------------------------------------------------
            _lstYearItems = new List<object>();
            for (int i = DateTime.Now.Year - 40; i <= DateTime.Now.Year + 40; i++)
                _lstYearItems.Add(new { Text = i.ToString(), Value = i.ToString() });
        }
        #endregion

        #region [ overrides ]
        protected override void OnInit(EventArgs e)
        {
            //register the script file.
            Page.ClientScript.RegisterClientScriptResource(GetType(), "Churchtoolkit.Utils.Controls.DateControl.js");
            base.OnInit(e);
        }
        protected override void CreateChildControls()
        {
            Controls.Add(_ddlDays);
            Controls.Add(_ddlMonths);
            Controls.Add(_ddlYears);
        }
        protected override void OnLoad(EventArgs e)
        {
            PopulateYear();
            PopulateMonth();
            PopulateDay();
            EnsureChildControls();
            // register a startup script to create new instatance of the js class
            Page.ClientScript.RegisterStartupScript(GetType(), ClientID,
                                                    StartupScript.FormatWith(_ddlMonths.ClientID,
                                                                             _ddlYears.ClientID,
                                                                             _ddlDays.ClientID), true);
            base.OnLoad(e);
        }
        #endregion

        #region [ public properties ]
        public DateTime SelectedDate
        {
            get
            {
                return DateTime.Parse(this.Month + "/" + this.Day + "/" + this.Year);
            }
            set
            {
                if (!value.Equals(DateTime.MinValue))
                {
                    this.Year = value.Year;
                    this.Month = value.Month;
                    this.Day = value.Day;
                }
            }
        }
        #endregion

        #region [ helpers ]
        private void PopulateDay()
        {
            var ddl = _ddlDays;
            ddl.Items.Clear();
            int days = DateTime.DaysInMonth(Year, Month);
            for (int i = 1; i <= days; i++)
                ddl.Items.Add(new ListItem { Text = i.ToString(), Value = i.ToString() });

            ddl.Items.FindByValue(DateTime.Now.Day.ToString()).Selected = true;
        }
        private void PopulateMonth()
        {
            if (_ddlMonths.Items.Count == 0)
            {
                _ddlMonths.DataSource = _lstMonthItems;
                _ddlMonths.DataTextField = "Text";
                _ddlMonths.DataValueField = "Value";
                _ddlMonths.DataBind();
                _ddlMonths.Items.FindByValue(DateTime.Now.Month.ToString()).Selected = true;
            }
        }
        private void PopulateYear()
        {
            if (_ddlYears.Items.Count == 0)
            {
                _ddlYears.DataSource = _lstYearItems;
                _ddlYears.DataTextField = "Text";
                _ddlYears.DataValueField = "Value";
                _ddlYears.DataBind();
                _ddlYears.Items.FindByValue(DateTime.Now.Year.ToString()).Selected = true;
            }
        }

        private int Day
        {
            get
            {
                return int.Parse(_ddlDays.SelectedItem.Value);
            }
            set
            {
                _ddlDays.ClearSelection();
                _ddlDays.Items.FindByValue(value.ToString()).Selected = true;
            }
        }
        private int Month
        {
            get
            {
                return int.Parse(_ddlMonths.SelectedItem.Value);
            }
            set
            {
                PopulateMonth();
                _ddlMonths.ClearSelection();
                _ddlMonths.Items.FindByValue(value.ToString()).Selected = true;
                PopulateDay();
            }
        }
        private int Year
        {
            get
            {
                return int.Parse(_ddlYears.SelectedItem.Value);
            }
            set
            {
                PopulateYear();
                _ddlYears.ClearSelection();
                _ddlYears.Items.FindByValue(value.ToString()).Selected = true;
            }
        }
        #endregion
    }
}